package veesing

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
)

var appKey string
var appId string

type ContentItem struct {
	Mobile    string        `json:"mobile"`
	Variables []interface{} `json:"variables"`
}

type SmsSendResult struct {
	ReturnStatus  string `json:"returnStatus"`
	Message       string `json:"message"`
	Remainpoint   string `json:"remainpoint"`
	TaskId        string `json:"taskId"`
	SuccessCounts string `json:"successCounts"`
}

func init() {
	appId = beego.AppConfig.DefaultString("appId", "BNKOR42VZGQL")
	appKey = beego.AppConfig.DefaultString("appKey", "QFZQF9LZ7NV9DX2B")
}

func SendSmsMsg(telephone string, smsId string, params ...interface{}) (result *SmsSendResult, err error) {
	url := "https://vip.veesing.com/smsApi/custom"
	req := httplib.Post(url)
	req.Param("appId", appId)
	req.Param("appKey", appKey)
	req.Param("smsId", smsId)
	//req.Param("sendTime", time.Now().Format(myType.TimeFormatLayout))
	var content = []ContentItem{{Mobile: telephone, Variables: params}}
	bytes, _ := json.Marshal(content)
	req.Param("content", string(bytes))
	var data []byte
	req.Debug(true)
	data, err = req.Bytes()
	logs.Info("SendSmsMsg request :%s", string(req.DumpRequest()))
	result = &SmsSendResult{}
	if err == nil {
		logs.Info("SendSmsMsg to %s response : %s", telephone, string(data))
		err = json.Unmarshal(data, result)
	} else {
		logs.Error("SendSmsMsg error:%s", telephone, err)
	}
	return
}

func SendSmsGroupMsg(telephone string, content string) (result *SmsSendResult, err error) {
	url := "https://vip.veesing.com/smsApi/group"
	req := httplib.Post(url)
	req.Param("appId", appId)
	req.Param("appKey", appKey)
	req.Param("phone", telephone)
	//req.Param("sendTime", time.Now().Format(myType.TimeFormatLayout))
	req.Param("content", content)
	var data []byte
	req.Debug(true)
	data, err = req.Bytes()
	logs.Info("SendSmsMsg request :%s", string(req.DumpRequest()))
	result = &SmsSendResult{}
	if err == nil {
		logs.Info("SendSmsMsg to %s response : %s", telephone, string(data))
		err = json.Unmarshal(data, result)
	} else {
		logs.Error("SendSmsMsg error:%s", telephone, err)
	}
	return
}
